package com.mocne.Common;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 统一返回对象
 *
 * @author lisf
 *
 */
public class ApiResponse implements Serializable {
    private static final long serialVersionUID = -4687189217609089082L;
    private int code;
    private boolean success;
    private String msg;
    private Object data;

    public static ApiResponse create(boolean success) {
        return create("", success);
    }

    public static ApiResponse create(String event, boolean success) {
        return new ApiResponse(event, success);
    }

    public static ApiResponse empty() {
        return new ApiResponse();
    }

    public ApiResponse() {

    }

    public ApiResponse(boolean success) {
        this.setSuccess(success);
    }

    public ApiResponse(String event, boolean success) {
        this.tip(event, success);
    }

    public int getCode() {
        return code;
    }

    public ApiResponse setCode(int code) {
        this.code = code;
        return this;
    }

    public boolean isSuccess() {
        return success;
    }

    public ApiResponse setSuccess(boolean success) {
        this.success = success;
        this.setCode(success ? 200 : 500);
        return this;
    }

    public ApiResponse tip(String event, boolean success) {
        this.setSuccess(success);
        this.setMsg(event + (success ? "-success" : "-fail"));
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public ApiResponse setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Object getData() {
        return data;
    }

    public ApiResponse setData(Object data) {
        this.data = data;
        return this;
    }

    @SuppressWarnings("unchecked")
    public ApiResponse putData(String key, Object value) {
        if (this.data == null) {
            this.data = new HashMap<String, Object>();
        }
        ((HashMap<String, Object>) this.data).put(key, value);
        return this;
    }

}
